<template>
  <div class="source">
    <div id="mapContext" ref="mapContext"></div>
    <div class="page-header">
      <div class="return" @click="$router.push('/index')">
        <img class="home" src="/images/icon/home.svg" alt="" />
        回到首页
      </div>
      <div class="title">{{ customTitle }}</div>
    </div>
    <div class="filter-box">
      <div class="filter">
        <div class="header" @click="toggleServiceExpanded">
          <img class="icon" src="/images/map/icon1.svg" alt="" />
          服务站点
          <img
            class="arrow"
            src="/images/map/arrow.svg"
            alt=""
            :class="{ expanded: isServiceExpanded }"
          />
        </div>
        <div class="body" v-show="isServiceExpanded">
          <div class="item" @click="toggleSelectAll">
            <div class="icon" :class="{ checked: isAllSelected, partial: isPartialSelected }">
              <div class="checkmark" v-if="isAllSelected">✓</div>
              <div class="dash" v-else-if="isPartialSelected">−</div>
            </div>
            全部
          </div>
          <div
            class="item"
            v-for="service in serviceList"
            :key="service.id"
            @click="toggleSelection(service.id)"
            :class="{ active: selectedItems.includes(service.id) }"
          >
            <div class="icon" :class="{ checked: selectedItems.includes(service.id) }">
              <div class="checkmark" v-if="selectedItems.includes(service.id)">✓</div>
            </div>
            {{ service.name }}
          </div>
        </div>
      </div>
      <div class="filter">
        <div class="header" @click="toggleResourceExpanded">
          <img class="icon" src="/images/map/icon2.svg" alt="" />
          公共资源
          <img
            class="arrow"
            src="/images/map/arrow.svg"
            alt=""
            :class="{ expanded: isResourceExpanded }"
          />
        </div>
        <div class="body" v-show="isResourceExpanded">
          <div class="item" @click="toggleResourceSelectAll">
            <div
              class="icon"
              :class="{ checked: isResourceAllSelected, partial: isResourcePartialSelected }"
            >
              <div class="checkmark" v-if="isResourceAllSelected">✓</div>
              <div class="dash" v-else-if="isResourcePartialSelected">−</div>
            </div>
            全部
          </div>
          <div
            class="item"
            v-for="resource in publicList"
            :key="resource.id"
            @click="toggleResourceSelection(resource.id)"
            :class="{ active: selectedResources.includes(resource.id) }"
          >
            <div class="icon" :class="{ checked: selectedResources.includes(resource.id) }">
              <div class="checkmark" v-if="selectedResources.includes(resource.id)">✓</div>
            </div>
            {{ resource.name }}
          </div>
        </div>
      </div>
    </div>
    <div class="tools">
      <div class="group">
        <div class="item">
          <div class="add" @click="handleMapScale('add')"></div>
        </div>
        <div class="item">
          <div class="sub" @click="handleMapScale('sub')"></div>
        </div>
      </div>
      <div class="item location" @click="getCurrentLocation">
        <img class="icon" src="/images/icon/location.svg" alt="" />
      </div>
    </div>
    <div class="service-button" @click="$router.push('/service')">
      <img class="icon" src="/images/icon/service.svg" alt="" />
      <img class="arrow" src="/images/icon/right-arrow.svg" alt="" />
    </div>
    <qrcode></qrcode>
    <div class="mask" v-show="showSpotDialog" @click="showSpotDialog = false"></div>
    <div class="marker-detail" v-show="showSpotDialog">
      <div class="header">
        <div class="name">{{ clickMarker.name }}</div>
        <div class="close" @click="showSpotDialog = false"></div>
      </div>
      <div class="tag">
        {{ clickMarker.category }}
      </div>
      <div class="content-list">
        <div class="item" v-if="clickMarker.content">
          <div class="name">简介:</div>
          <div class="content">{{ clickMarker.content }}</div>
        </div>
        <div class="item" v-if="clickMarker.address">
          <div class="name">地址:</div>
          <div class="content">{{ clickMarker.address }}</div>
        </div>
        <div class="item" v-if="clickMarker.trainingInstitution">
          <div class="name">培训机构:</div>
          <div class="content">{{ clickMarker.trainingInstitution }}</div>
        </div>
        <div class="item" v-if="clickMarker.trainingType">
          <div class="name">培训工种:</div>
          <div class="content">{{ clickMarker.trainingType }}</div>
        </div>
        <div class="item" v-if="clickMarker.talentManager">
          <div class="name">培训工种:</div>
          <div class="content">{{ clickMarker.talentManager }}</div>
        </div>
        <div class="list">
          <div class="item" v-if="clickMarker.contact">
            <div class="name">联系人:</div>
            <div class="content">{{ clickMarker.contact }}</div>
          </div>
          <div class="item" v-if="clickMarker.contactPerson">
            <div class="name">联系人:</div>
            <div class="content">{{ clickMarker.contactPerson }}</div>
          </div>
        </div>
        <div class="item jump-link" v-if="clickMarker.link">
          <div>
            <div class="name">跳转链接:</div>
            <div class="content">{{ clickMarker.link }}</div>
          </div>
        </div>
      </div>
      <div
        class="button"
        @click="handleSpotClick(clickMarker.serviceIdList[0])"
        v-if="clickMarker?.serviceIdList?.length > 0"
      >
        <img class="icon" src="/images/icon/service.svg" alt="" />
        办理业务
      </div>
    </div>
  </div>
</template>
<script setup>
import qrcode from '@/components/qrcode.vue'
import { onMounted, ref, computed, watch, h } from 'vue'
import { getFilterList, getSpotList } from '@/api/data'
import { getCustomTitle } from '@/utils/customStorage.js'
import { useRoute, useRouter } from 'vue-router'
const mapContext = ref(null)
var map = null
var markerLayer = null
var labelLayer = null
// 自定义标题
const customTitle = ref('椒江区人才社区地图')
// 服务站点选择状态
const selectedItems = ref([])
const serviceList = ref([])
// 公共资源选择状态
const selectedResources = ref([])
const publicList = ref([])
// 控制筛选器展开/收起状态
const isServiceExpanded = ref(false)
const isResourceExpanded = ref(false)
// 计算是否全选
const isAllSelected = computed(() => {
  return (
    serviceList.value.length > 0 &&
    serviceList.value.every((item) => selectedItems.value.includes(item.id))
  )
})
// 计算是否半选状态
const isPartialSelected = computed(() => {
  return selectedItems.value.length > 0 && !isAllSelected.value
})
const isResourceAllSelected = computed(() => {
  return (
    publicList.value.length > 0 &&
    publicList.value.every((resource) => selectedResources.value.includes(resource.id))
  )
})
// 计算资源是否半选状态
const isResourcePartialSelected = computed(() => {
  return selectedResources.value.length > 0 && !isResourceAllSelected.value
})
// 切换单个项目选择状态
const toggleSelection = (itemId) => {
  const index = selectedItems.value.indexOf(itemId)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(itemId)
  }
}
// 切换全选状态
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedItems.value = []
  } else {
    selectedItems.value = [...serviceList.value.map((item) => item.id)]
  }
}
// 切换单个资源选择状态
const toggleResourceSelection = (resourceId) => {
  const index = selectedResources.value.indexOf(resourceId)
  if (index > -1) {
    selectedResources.value.splice(index, 1)
  } else {
    selectedResources.value.push(resourceId)
  }
}
// 切换资源全选状态
const toggleResourceSelectAll = () => {
  if (isResourceAllSelected.value) {
    selectedResources.value = []
  } else {
    selectedResources.value = [...publicList.value.map((resource) => resource.id)]
  }
}
// 切换服务站点筛选器展开状态
const toggleServiceExpanded = () => {
  isServiceExpanded.value = !isServiceExpanded.value
}
// 切换公共资源筛选器展开状态
const toggleResourceExpanded = () => {
  isResourceExpanded.value = !isResourceExpanded.value
}
// 地图缩放控制
const handleMapScale = (type) => {
  if (!map) return
  const currentZoom = map.getZoom()
  if (type === 'add') {
    map.setZoom(currentZoom + 1)
  } else {
    map.setZoom(currentZoom - 1)
  }
}
// 获取当前位置
const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude
      const lng = position.coords.longitude
      map.setCenter(new TMap.LatLng(lat, lng))
    })
  }
}
const spotList = ref([])
// 监听选择变化，可以在这里处理地图数据筛选
watch(
  [selectedItems, selectedResources, spotList],
  ([newItems, newResources, newSpotList]) => {
    // 在这里可以根据选择结果更新地图上的标记点
    // 如果没有任何筛选条件，则显示所有点位
    const categoryArray = [...newItems, ...newResources]
    let filterSpotList = newSpotList
    if (categoryArray.length == 0) {
      handleAddMarkers(filterSpotList)
      return
    }
    if (categoryArray.length > 0) {
      filterSpotList = filterSpotList.filter((item) => {
        // 如果选中了服务站点、公共资源，则返回对应类别的点位
        if (categoryArray.includes(item.categoryId)) {
          return true
        }
        return false
      })
    }
    handleAddMarkers(filterSpotList)
  },
  { deep: true },
)
const markerList = ref([])
const clickMarkerId = ref(-1)
const clickMarker = computed(() => {
  if (clickMarkerId.value == -1) return {}
  return markerList.value.find((item) => item.id == clickMarkerId.value) || {}
})
const handleSpotClick = (id) => {
  showSpotDialog.value = false
  router.push({
    path: `/service`,
    query: {
      id,
    },
  })
}
import { handleProxy } from '@/api/data.js'
const handleAddMarkers = (data) => {
  // 清空现有标记和标签
  if (markerLayer) {
    markerLayer.setGeometries([])
  }
  if (labelLayer) {
    labelLayer.setGeometries([])
  }

  markerList.value = data.map((item) => {
    return {
      ...item,
      icon: handleProxy(item.icon),
      id: item.id,
    }
  })

  if (markerList.value.length === 0) {
    return
  }

  // 构建腾讯地图标记点数据
  const geometries = []
  const labelGeometries = []
  const styles = {}

  for (let i = 0; i < markerList.value.length; i++) {
    const item = markerList.value[i]

    // 创建标记点
    const geometry = {
      id: item.id,
      styleId: `marker_${item.id}`,
      position: new TMap.LatLng(item.lat, item.lng),
      properties: {
        title: item.name,
      },
    }

    geometries.push(geometry)

    // 创建标签
    const labelGeometry = {
      id: `label_${item.id}`,
      styleId: 'label',
      position: new TMap.LatLng(item.lat, item.lng),
      content: item.name,
      properties: {
        title: item.name,
      },
    }

    labelGeometries.push(labelGeometry)

    // 为每个标记创建自定义样式（如果有自定义图标）
    if (item.icon) {
      styles[`marker_${item.id}`] = new TMap.MarkerStyle({
        width: 60,
        height: 60,
        anchor: { x: 30, y: 60 },
        src: item.icon,
      })
    }
  }

  // 设置默认样式
  styles['default'] = new TMap.MarkerStyle({
    width: 60,
    height: 60,
    anchor: { x: 30, y: 60 },
    color: '#13B7A4',
  })

  // 添加标记到地图
  markerLayer.setGeometries(geometries)
  markerLayer.setStyles(styles)

  // 添加标签到地图
  labelLayer.setGeometries(labelGeometries)
  labelLayer.setStyles({
    label: new TMap.LabelStyle({
      color: '#fff',
      size: 16,
      backgroundColor: '#13B7A4',
      padding: '8px 16px',
      offset: { x: 0, y: -75 },
      angle: 0,
      alignment: 'center',
      verticalAlignment: 'middle',
      borderRadius: 18,
      borderWidth: 2,
      borderColor: '#ffffff',
    }),
  })
}
const showSpotDialog = ref(false)
const eventClick = (event) => {
  showSpotDialog.value = true
  // 处理标签点击事件，标签ID格式为 label_${id}
  const geometryId = event.geometry.id
  if (geometryId.toString().startsWith('label_')) {
    clickMarkerId.value = geometryId.toString().replace('label_', '')
  } else {
    clickMarkerId.value = geometryId
  }
}
const route = useRoute()
const router = useRouter()
onMounted(() => {
  // 获取自定义标题
  customTitle.value = getCustomTitle()

  //定义map变量，调用 TMap.Map() 构造函数创建地图
  map?.destroy() // 销毁旧地图实例
  map = new TMap.Map(mapContext.value, {
    center: new TMap.LatLng(28.64621, 121.400343), //设置地图中心点坐标
    zoom: 15, //设置地图缩放级别
  })
  // 移除缩放控件
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ZOOM)
  // 移除旋转控件
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.ROTATION)
  map.removeControl(TMap.constants.DEFAULT_CONTROL_ID.SCALE)

  //初始化marker图层
  markerLayer = new TMap.MultiMarker({
    id: 'marker-layer',
    map: map,
  })
  markerLayer.on('click', eventClick)

  // 初始化标签图层
  labelLayer = new TMap.MultiLabel({
    id: 'label-layer',
    map: map,
  })
  labelLayer.on('click', eventClick)

  // 获取筛选数据
  getFilterList()
    .then((res) => {
      publicList.value = res.data.data.publicList || []
      serviceList.value = res.data.data.serviceList || []

      // 如果页面携带分类ID参数，自动勾选对应的服务站点或公共资源
      if (route.query.id) {
        const categoryId = Number(route.query.id)

        // 检查是否为服务站点分类
        const isServiceCategory = serviceList.value.some((service) => service.id === categoryId)

        // 检查是否为公共资源分类
        const isResourceCategory = publicList.value.some((resource) => resource.id === categoryId)

        if (isServiceCategory && !selectedItems.value.includes(categoryId)) {
          selectedItems.value.push(categoryId)
        } else if (isResourceCategory && !selectedResources.value.includes(categoryId)) {
          selectedResources.value.push(categoryId)
        }
      }

      return getSpotList()
    })
    .then((res) => {
      spotList.value = res.data.data || []
    })
    .catch((error) => {
      console.error('获取筛选数据失败:', error)
      // 设置默认数据
      serviceList.value = []
      publicList.value = []

      return getSpotList()
    })
    .then((res) => {
      if (res) {
        spotList.value = res.data.data || []
      }
    })
})
</script>
<style scoped lang="scss">
.source {
  position: relative;
  width: 1920px;
  height: 100vh;
  overflow: hidden;
  #mapContext {
    width: 1920px;
    height: 100vh;
  }
  .page-header {
    z-index: 1000;
    position: absolute;
    top: 0;
  }
  .filter-box {
    z-index: 1002;
    position: absolute;
    width: 192px;
    height: auto;
    max-height: 600px;
    top: 84px;
    left: 24px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    .filter {
      width: 200px;
      .header {
        cursor: pointer;
        height: 48px;
        border-radius: 8px;
        gap: 8px;
        padding-right: 16px;
        padding-left: 16px;
        display: flex;
        align-items: center;
        background: #ffffff;
        font-family: PingFang SC;
        font-weight: 500;
        font-style: Medium;
        font-size: 16px;
        color: #323333;
        .icon {
          width: 24px;
          height: 24px;
        }
        .arrow {
          margin-left: auto;
          width: 12px;
          height: 12px;
          transform: rotate(180deg);
          transition: transform 0.3s ease;

          &.expanded {
            transform: rotate(0deg);
          }
        }
      }
      .body {
        margin-top: 8px;
        border-radius: 8px;
        padding: 4px;
        gap: 4px;
        display: flex;
        flex-direction: column;
        background: #ffffff;
        transition: all 0.3s ease;
        .item {
          cursor: pointer;
          border-radius: 6px;
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px;
          transition: all 0.2s ease;
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #323333;

          &:hover {
            background: #f5f7fa;
          }

          &.active {
            background: #38d3c31a;
            border: 1px solid #38d3c3;
          }

          .icon {
            position: relative;
            width: 16px;
            height: 16px;
            border-radius: 4px;
            border: 2px solid #d9d9d9;
            background: #ffffff;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;

            &.checked {
              border-color: #13b7a4;
              background: #13b7a4;
            }

            &.partial {
              border-color: #13b7a4;
              background: #13b7a4;
            }

            .checkmark {
              color: #ffffff;
              font-size: 10px;
              font-weight: bold;
              line-height: 1;
            }

            .dash {
              color: #ffffff;
              font-size: 12px;
              font-weight: bold;
              line-height: 1;
            }
          }
        }
      }
    }
  }
  .tools {
    position: absolute;
    top: 84px;
    left: 1840px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    z-index: 1002;
    .group {
      border-radius: 8px;
      overflow: hidden;
      background: #ffffffe5;
      backdrop-filter: blur(4px);
      position: relative;
      &::after {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        content: '';
        width: 32px;
        height: 1px;
        background: #0000000d;
      }
    }

    .item {
      width: 56px;
      height: 56px;
      background: #ffffffe5;
      backdrop-filter: blur(4px);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      &.location {
        border-radius: 8px;
        .icon {
          width: 24px;
          height: 24px;
        }
      }

      .add,
      .sub {
        width: 24px;
        height: 24px;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          width: 16px;
          height: 2px;
          background: #13b7a4;
        }
      }

      .add::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 2px;
        height: 16px;
        background: #13b7a4;
      }
    }
  }
  .service-button {
    cursor: pointer;
    position: absolute;
    z-index: 1002;
    right: 0px;
    top: 702px;
    transform: translateY(-50%);
    width: 80px;
    height: 68px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    border-width: 2px, 0px, 2px, 2px;
    border-style: solid;
    border-color: #ffffff54;
    border-top-left-radius: 12px;
    border-bottom-left-radius: 12px;
    background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);
    box-shadow: 0px 4px 8px 0px #38d3c340;

    .icon {
      width: 36px;
      height: 36px;
      flex-shrink: 0;
    }

    .arrow {
      height: 16px;
      width: 16px;
    }
  }
  .qrcode {
    position: absolute;
    width: 192px;
    height: 242px;
    top: 814px;
    left: 1704px;
    border-radius: 16px;
    border: 1px solid #fff;
    padding: 16px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    background: #ffffffcc;
    backdrop-filter: blur(8px);
    box-shadow: 0px 8px 16px 0px #0000001a;
    .title {
      font-family: PingFang SC;
      font-weight: 500;
      font-style: Medium;
      font-size: 14px;
      color: #323333;
    }
    .code {
      width: 160px;
      height: 160px;
    }
    .tips {
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 12px;
      line-height: 18px;
      color: #969799;
    }
  }
  .mask {
    position: fixed;
    top: 176rpx;
    left: 0;
    width: 100vw;
    height: calc(100vh - 176rpx);
    background: #00000055;
  }
  .marker-detail {
    position: absolute;
    z-index: 1000;
    width: 400px;
    top: 309px;
    left: 760px;
    padding: 24px;
    background: #fff;
    border-radius: 8px;

    .header {
      position: relative;
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 50px;

      &::before {
        position: absolute;
        content: '';
        width: 400px;
        bottom: 0;
        left: -25px;
        height: 2px;
        background: #0000000d;
      }

      .name {
        font-family: PingFang SC;
        font-weight: 500;
        font-style: Medium;
        font-size: 30rpx;
        color: #333333;
      }

      .close {
        cursor: pointer;
        margin-top: 2px;
        position: relative;
        width: 24px;
        height: 24px;

        &::after {
          position: absolute;
          left: 50%;
          width: 2px;
          height: 100%;
          margin-left: -1px;
          content: '';
          background: #94979c;
          rotate: -45deg;
        }

        &::before {
          position: absolute;
          left: 50%;
          width: 2px;
          height: 100%;
          margin-left: -1px;
          content: '';
          background: #94979c;
          rotate: 45deg;
        }
      }
    }

    .tag {
      margin-top: 24px;
      width: fit-content;
      height: 28px;
      border-radius: 4px;
      text-align: center;
      padding: 4px 8px;
      background-color: #38d3c31a;
      font-family: PingFang SC;
      font-weight: 500;
      font-style: Medium;
      font-size: 14px;
      color: #13b7a4;
    }

    .content-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .item {
      margin-top: 24px;

      .name {
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 14px;
        color: #94979c;
      }

      .content {
        margin-top: 4px;
        font-family: PingFang SC;
        font-weight: 400;
        font-style: Regular;
        font-size: 16px;
        color: #333333;
        word-break: break-all;
        word-wrap: break-word;
        white-space: pre-wrap;
      }

      &.jump-link {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 12px;

        .copy {
          cursor: pointer;
          padding: 6px 12px;
          background: #13b7a4;
          color: white;
          border-radius: 4px;
          font-size: 12px;
          white-space: nowrap;
          transition: all 0.3s ease;

          &:hover {
            background: #0f9d8a;
          }

          .text {
            font-family: PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #ffffff;
          }
        }
      }
    }

    .button {
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      margin-top: 24px;
      width: 100%;
      height: 48px;
      border-radius: 6px;
      color: #ffffff;
      background: linear-gradient(270deg, #44d4a8 0%, #30d1e6 100%);

      .icon {
        width: 20px;
        height: 20px;
      }
    }
  }
}
</style>
